<?php

class Paycallback extends BZ_Controller
{
    public function _init()
    {
        $this->load->helper('common');
        $this->load->library('alipay/alipaypc', null, 'alipaypc');
        $this->load->model('pay_failure_log_model', 'pay_failure_log');
        $this->load->model('pay_method_model', 'pay_method');
        $this->load->model('user_account_model', 'user_account');
        $this->load->model('account_log_model', 'account_log');
        $this->load->model('deposit_model', 'deposit');
    }

    /*支付宝回调异步*/
    public function alipayNotify()
    {
        $response = $this->alipaypc->responseAlipayNotify();
        $depositId = $response;
        $depositInfo = $this->_depositIsCorrect($depositId);
        if ($response) {
            $this->db->trans_begin();
            $userAccount = $this->user_account->findByUid($depositInfo->uid)->row();

            //更新充值状态 增加用户可提现金额
            $depositData = array('amount_carry' => $userAccount->amount_carry, 'state' => 2);
            $state = $this->deposit->updateState($depositInfo->deposit_id, $depositInfo->uid, $depositData);
            $account = $this->user_account->userDeposit($depositInfo->uid, $depositInfo->amount);
            $accountLog = $this->account_log->insertAccountLogDeposit($depositInfo, $userAccount->amount_carry);
            if (!$state || !$account || !$accountLog || $this->db->trans_status() === FALSE)
            {
                $this->db->trans_rollback();
                $this->redirect('home/account/fail');
            }
            else
            {
                $this->db->trans_commit();
                $this->redirect('home/account/success');
            }
        } else {
            $result = $this->pay_failure_log->findByOrderSn($depositId);
            if (!$result) { //保存错误日志。
                $last_id = $this->pay_failure_log->insertPayFailureLog($depositId, $this->input->post(), $response);
            }
        }
    }


    /* 微信jsapi支付回调*/
    public function wxNotify()
    {
        include_once(getcwd()."/application/libraries/wxpay/WxPayPubHelper/WxPayPubHelper.php");
        $notify = new Notify_pub();//使用通用通知接口
        $xml    = file_get_contents('php://input', 'r');   //存储微信的回调
        $notify->saveData($xml);

        //验证签名，并回应微信。
        //对后台通知交互时，如果微信收到商户的应答不是成功或超时，微信认为通知失败，
        //微信会通过一定的策略（如30分钟共8次）定期重新发起通知，
        //尽可能提高通知的成功率，但微信不保证通知最终能成功。
        if( $notify->checkSign() == FALSE ){
            $notify->setReturnParameter("return_code","FAIL");  //返回状态码
            $notify->setReturnParameter("return_msg","签名失败");  //返回信息
        }else{
            $notify->setReturnParameter("return_code","SUCCESS");//设置返回码
        }
        $returnXml = $notify->returnXml();
        echo $returnXml;      //echo为微信返回值   不能更改   不能删除

        if($notify->checkSign() == TRUE)
        {
            if ($notify->data["return_code"] == "FAIL" || $notify->data["result_code"] == "FAIL")
            {
                $return_param = "【通信出错】【业务出错】:\n".$xml."\n";
                $result = $this->pay_failure_log->findByOrderSn($notify->data["out_trade_no"]);
                if (!$result) { //保存错误日志。
                    $last_id = $this->pay_failure_log->insertPayFailureLog($notify->data["out_trade_no"], $return_param, "微信支付报错");
                }
            }else{
                $depositId = $notify->data["out_trade_no"];
                $depositInfo = $this->_depositIsCorrect($depositId);
                $this->db->trans_begin();
                $userAccount = $this->user_account->findByUid($depositInfo->uid)->row();
                
                //更新充值状态 增加用户可提现金额
                $depositData = array('amount_carry' => $userAccount->amount_carry, 'state' => 2);
                $state = $this->deposit->updateState($depositInfo->deposit_id, $depositInfo->uid, $depositData);
                $account = $this->user_account->userDeposit($depositInfo->uid, $depositInfo->amount);
                $accountLog = $this->account_log->insertAccountLogDeposit($depositInfo, $userAccount->amount_carry);
                if (!$state || !$account || !$accountLog || $this->db->trans_status() === FALSE)
                {
                    $this->db->trans_rollback();
                    $this->redirect('home/account/fail');
                }
                else
                {
                    $this->db->trans_commit();
                    $this->redirect('home/account/success');
                }
            }
        }
    }

    /**
     * 充值信息是否正确
     */
    private function _depositIsCorrect($id)
    {
        if ( empty($id) )
        {
            $this->alertJumpPre('充值异常');
        }
        $result = $this->deposit->findById($id);
        if ($result->num_rows() == 0)
        {
            $this->alertJumpPre('充值异常');
        }
        $depositInfo = $result->row();
        if ($depositInfo->state == 2)//如果支付过
        {
            $this->redirect('home/account/success');
        }
        return $depositInfo;
    }
}

